package com.baibei.ebec.welfare.index;

import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.baibei.ebec.home.R;
import com.baibei.ebec.home.R2;
import com.baibei.ebec.moments.activity.MomentsDetailActivity;
import com.baibei.ebec.sdk.BuildConfig;
import com.baibei.ebec.sdk.TokenInfo;
import com.baibei.model.UserInfo;
import com.baibei.module.AppRouter;
import com.baibei.module.BasicFragment;
import com.baibei.widget.CommonRefreshLayout;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.rae.swift.session.SessionManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.onekeyshare.ShareContentCustomizeCallback;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by tang on 2017/12/29.
 */

public class IndexWelfareFragment extends BasicFragment {


    Unbinder unbinder;
    @BindView(R2.id.iv_banner)
    ImageView ivBanner;
    @BindView(R2.id.iv_rec_tic88)
    ImageView ivRecTic88;
    @BindView(R2.id.tv_reg_num)
    TextView tvRegNum;
    @BindView(R2.id.iv_rec_tic28)
    ImageView ivRecTic28;
    @BindView(R2.id.tv_trade_num)
    TextView tvTradeNum;
    @BindView(R2.id.refresh_layout)
    CommonRefreshLayout refreshLayout;
    private int iv88Status = 0;
    private int iv28Status = 0;
    private String recTic88Url;
    private String recTic28Url;
    private String xtUrl;
    private String zxUrl;

    public static IndexWelfareFragment newInstance() {
        IndexWelfareFragment fragment = new IndexWelfareFragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public int getLayoutId(Bundle bundle) {
        return R.layout.fragment_welfare_index;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        init();
        return rootView;
    }

    private void init() {
        reLoadInfo();
        refreshLayout.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout ptrFrameLayout) {
                reLoadInfo();
                refreshLayout.refreshComplete();
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    private void popShare() {
        OnekeyShare oks = new OnekeyShare();
        oks.disableSSOWhenAuthorize();
        oks.setTitle("点点淘金，呼朋唤友来淘金");
        // titleUrl QQ和QQ空间跳转链接
        oks.setTitleUrl(getShareUrl());
        // text是分享文本，所有平台都需要这个字段
        oks.setText("8.8元订黄金，双向赚，上手简单，马上体验");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
//        oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        Bitmap image = null;
        AssetManager assets = getResources().getAssets();
        try {
            InputStream is = assets.open("logo.png");
            image = BitmapFactory.decodeStream(is);
            is.close();
            oks.setImageData(image);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // url在微信、微博，Facebook等平台中使用
        oks.setUrl(getShareUrl());
        //分渠道针对性区分文本内容
        oks.setShareContentCustomizeCallback(new ShareContentCustomizeCallback() {
            @Override
            public void onShare(Platform platform, Platform.ShareParams shareParams) {
                if ("ShortMessage".equals(platform.getName())) {
                    shareParams.setText("8.8元订黄金，双向赚，上手简单，马上体验。" + getShareUrl());
                }
                if ("QQ".equals(platform.getName())) {
                    shareParams.setTitle("点点淘金，呼朋唤友来淘金");
                    shareParams.setText("8.8元订黄金，双向赚，上手简单，马上体验");
                    shareParams.setTitleUrl(getShareUrl());
                }

            }
        });
        // 启动分享GUI
        oks.show(getContext());
    }

    private String getShareUrl() {
//        TokenInfo userToken = SessionManager.getDefault().getUserToken();
//        String token = userToken.getAccessToken();
        UserInfo userInfo = SessionManager.getDefault().getUser();
        int userId = userInfo.getUserId();
        return BuildConfig.API_BASE_URL + "ddtj/index.html?invitationCode=" + userId +
                "&exchange=CB_GUOXIANG&memberChannel=999";
    }

    private void reLoadInfo() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String url = BuildConfig.API_BASE_URL + "app/fl/api/index";
                OkHttpClient client = new OkHttpClient();
                HashMap<String, String> map = new HashMap<>();
                if (SessionManager.getDefault().getUser() == null || SessionManager.getDefault().getUserToken() == null) {
                    return;
                }
                map.put("accessToken", ((TokenInfo) (SessionManager.getDefault().getUserToken())).getAccessToken());
                map.put("userId", ((UserInfo) SessionManager.getDefault().getUser()).getUserId() + "");
                Gson gson = new Gson();
                String s = gson.toJson(map);
                RequestBody requestBody = FormBody.create(MediaType.parse("applicaiton/json; charset=utf-8"), s);
                Request request = new Request.Builder()
                        .post(requestBody)
                        .url(url)
                        .build();

                Call call = client.newCall(request);
                try {
                    Response response = call.execute();
                    final JSONObject responseInfo = new JSONObject(response.body().string());
//                    Log.i("rectich",responseInfo.toString());
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            reLoadView(responseInfo);
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    private void reLoadView(JSONObject responseInfo) {
        //请求失败
        if (!"SUCCESS".equals(responseInfo.optString("code"))) {
            return;
        }
        //代理用户
        if (!"Y".equals(responseInfo.optString("state"))) {
            return;
        }
        //替换banner图
        Glide.with(getContext()).load(responseInfo.optString("title")).into(ivBanner);

        JSONObject job = responseInfo.optJSONObject("data");

        if (job == null) {
            //可能会有种种概率微小的原因导致没有data数据
            return;
        }
        //学堂、资讯的url
        xtUrl = job.optString("xtUrl");
        zxUrl = job.optString("zxUrl");

        if (job.optString("yqnum") != null) {
            tvRegNum.setText("您已邀请注册用户：" + job.optString("yqnum") + "人");
        }
        if (job.optString("cashnum") != null) {
            tvTradeNum.setText("您已邀请现金订购用户：" + job.opt("cashnum") + "人");
        }
        //设置两个领券按钮的状态
        iv88Status = job.optInt("yqticket");
        setRecTicButton(iv88Status, ivRecTic88);

        iv28Status = job.optInt("cashticket");
        setRecTicButton(iv28Status, ivRecTic28);

        //获取领券接口url
        recTic88Url = job.optString("yqticketUrl");
        recTic28Url = job.optString("cashticketUrl");
    }

    private void setRecTicButton(int status, ImageView iv) {
        switch (status) {
            case 0:
                iv.setImageResource(R.drawable.tic_0);
                break;
            case 1:
                iv.setImageResource(R.drawable.tic_1);
                break;
            case 2:
                iv.setImageResource(R.drawable.tic_2);
                break;
        }
    }

//    @Override
//    public void onResume() {
//        super.onResume();
//        reLoadInfo();
//    }

    //fragment切换时刷新数据，好处是实时知道券的可领取状态，坏处是每次进入都要刷新的闪顿影响体验
//    @Override
//    public void setUserVisibleHint(boolean isVisibleToUser) {
//        super.setUserVisibleHint(isVisibleToUser);
//        if (isVisibleToUser){
//            reLoadInfo();
//        }
//    }


    @OnClick({R2.id.ll_ddxt, R2.id.ll_ddzx, R2.id.ll_ddylb,R2.id.ll_ddq, R2.id.iv_rec_tic88, R2.id.iv_rec_tic28, R2.id.iv_toshare})
    public void onViewClicked(View view) {
        if (view.getId() == R.id.ll_ddxt) {
//            String xt = (xtUrl != null ? xtUrl : "http://www.dd.shzstr.cn/learn/index.html");
            String xt = "http://www.dd.shzstr.cn/learn/index.html";
            AppRouter.routeToWeb(getContext(), "点点学堂", xt);
        } else if (view.getId() == R.id.ll_ddzx) {
//            String zx = (zxUrl != null ? zxUrl : "http://mp.weixin.qq.com/mp/homepage?__biz=MzUxMjYyMDk3Nw==&hid=2&sn=ab1046f525564604f07f2bf1af92f2a9#wechat_redirect");
            String zx = "http://mp.weixin.qq.com/mp/homepage?__biz=MzUxMjYyMDk3Nw==&hid=2&sn=ab1046f525564604f07f2bf1af92f2a9#wechat_redirect";
            AppRouter.routeToWeb(getContext(), "点点资讯", zx);
        } else if (view.getId() == R.id.ll_ddylb){
            AppRouter.routeToWelfareRank(getContext());
        } else if (view.getId() == R.id.ll_ddq){
            AppRouter.routeToWelfareMoments(getContext());
        } else if (view.getId() == R.id.iv_rec_tic88) {
            if (iv88Status != 1 || "".equals(recTic88Url)) {
                return;
            }
            recTic(recTic88Url);
        } else if (view.getId() == R.id.iv_rec_tic28) {
            if (iv28Status != 1 || "".equals(recTic28Url)) {
                return;
            }
            recTic(recTic28Url);
        } else if (view.getId() == R.id.iv_toshare) {
            popShare();
        }
    }

    private void recTic(final String url) {
        new Thread(new Runnable() {
            @Override
            public void run() {
//                Log.i("rectichurl",url);
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(url)
                        .build();
                Call call = client.newCall(request);
                try {
                    Response response = call.execute();
                    JSONObject jsonObject = new JSONObject(response.body().string());
//                    Log.i("rectich1",jsonObject.toString());
                    String msg = jsonObject.optString("message");
                    if (!"SUCCESS".equals(jsonObject.optString("code"))) {
                        ToastOnUiThread(msg);
                        return;
                    }
                    int num = jsonObject.optInt("num");
                    ToastOnUiThread(msg + ",还剩" + num + "张可领取");
                    reLoadInfo();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void ToastOnUiThread(final String s) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getContext(), s, Toast.LENGTH_LONG).show();
            }
        });
    }
}
